from io import BytesIO
import qrcode
from extension import db

import base64
import json
from flask import Blueprint, jsonify, request
from io import BytesIO
import datetime
from sqlalchemy import null
from models import Account, Borrow, Book
from decimal import Decimal

borrow_bp = Blueprint('borrow', __name__)


@borrow_bp.route('/<string:username>/<int:bookId>', methods=['GET'])
def borrowBook(username, bookId):
    book = Book.query.filter_by(bookId=bookId).first()
    if book:
        bookName = book.bookName

        user = Account.query.filter_by(username=username).first()
        quantity = book.quantity
        username = user.username
        admin = user.admin
        print('admin=')
        print(admin)
        borrowBookNum = user.borrowBookNum

        startDate = datetime.date.today()
        endDate = startDate + datetime.timedelta(days=30)
        im = qrcode.make(bookId)
        img = BytesIO()
        im.save(img, format='PNG')
        img_bytes = img.getvalue()
        # 将 PNG 格式的二进制数据转换为 base64 编码的字符串
        img_base64_str = base64.b64encode(img_bytes).decode('utf-8')

        #学生借书
        if admin == 0:
            if quantity > 0:
                if borrowBookNum < 6:
                    #可以借书
                    borrow = Borrow(username=username, bookName=bookName, startDate=startDate, endDate=endDate,
                                    code=img_base64_str, returnBook=0, getBook=0, evaluation=-1)
                    db.session.add(borrow)
                    user.borrowBookNum = borrowBookNum + 1
                    book.quantity = quantity - 1
                    db.session.add(user)
                    db.session.add(book)
                    db.session.commit()
                    return {
                        "code": "0",
                        "message": "SUCCESS",
                        "data": img_base64_str
                    }
                else:
                    return {
                        "code": "1",
                        "message": "ERROR",
                        "data": "借书数量已达上限6本"
                    }
            else:
                return {
                    "code": "1",
                    "message": "ERROR",
                    "data": "图书库存不足"
                }
        #老师/管理员借书
        else:
            if quantity > 0:
                if borrowBookNum < 10:
                    #可以借书
                    borrow = Borrow(username=username, bookName=bookName, startDate=startDate, endDate=endDate,
                                    code=img_base64_str, returnBook=0, getBook=0, evaluation=-1)
                    db.session.add(borrow)
                    user.borrowBookNum = borrowBookNum + 1
                    book.quantity = quantity - 1
                    db.session.add(user)
                    db.session.add(book)
                    db.session.commit()
                    return {
                        "code": "0",
                        "message": "SUCCESS",
                        "data": img_base64_str
                    }
                else:
                    return {
                        "code": "1",
                        "message": "ERROR",
                        "data": "借书数量已达上限10本"
                    }
            else:
                return {
                    "code": "1",
                    "message": "ERROR",
                    "data": "图书库存不足"
                }
    else:
        return {
            "code": "1",
            "message": "ERROR",
            "data": "未找到指定ID书本"
        }


@borrow_bp.route('returnBookList/<string:username>/<int:page>', methods=['GET'])
def returnBookList(username, page):
    borrowList = Borrow.query.filter_by(username=username).all()
    resultList = []  # 存储整个书籍对象
    bookList = []  # 存储整个书籍对象

    for borrow in borrowList:
        book = Book.query.filter_by(bookName=borrow.bookName).first()
        bookList.append(book)
        resultList.append({
            "borrowId": borrow.borrowId,
            "bookId": book.bookId,
            "bookName": book.bookName,
            "author": book.author,
            "startDate": borrow.startDate.strftime('%Y-%m-%d'),
            "endDate": borrow.endDate.strftime('%Y-%m-%d'),
            "returnBook": borrow.returnBook,
            "getBook": borrow.getBook
        })

    count = len(bookList)
    # 每页显示的条目数为5
    pre_page = 5
    total_pages = count // pre_page + (1 if count % pre_page != 0 else 0)  # 总页数
    if page > total_pages or page == 0:
        return jsonify({
            "code": "1",
            "message": "ERROR",
            "data": "未找到指定页数"
        })

    # 计算起始索引和结束索引
    start = (page - 1) * pre_page
    end = min(start + pre_page, count)
    # 获取当前页的结果数据
    current_page_results = resultList[start:end]

    return jsonify({
        "code": "0",
        "message": "SUCCESS",
        "data": {
            "borrows": current_page_results,
        }
    })


@borrow_bp.route('returnBook/<string:username>/<int:bookId>', methods=['GET'])
def returnBook(username, bookId):
    book = Book.query.filter_by(bookId=bookId).first()
    if book:
        borrowBook = Borrow.query.filter_by(username=username, bookName=book.bookName).first()
        if borrowBook:
            return {
                "code": "0",
                "message": "SUCCESS",
                "data": {
                    "borrowId": borrowBook.borrowId,
                    "username": borrowBook.username,
                    "bookName": book.bookName,
                    "startDate": borrowBook.startDate.strftime('%Y-%m-%d'),
                    "endDate": borrowBook.endDate.strftime('%Y-%m-%d'),
                    "code": borrowBook.code,
                    "returnBook": borrowBook.returnBook,
                    "getBook": borrowBook.getBook,
                    "evaluation": borrowBook.evaluation
                }
            }
        else:
            return {
                "code": "1",
                "message": "ERROR",
                "data": "未找到指定ID书本"
            }
    else:
        return {
            "code": "1",
            "message": "ERROR",
            "data": "未找到指定ID书本"
        }


@borrow_bp.route('admin/getBook/<string:username>/<int:bookId>', methods=['GET'])
def getBookStatus(username, bookId):
    book = Book.query.filter_by(bookId=bookId).first()
    if book:
        book1 = Borrow.query.filter_by(username=username, bookName=book.bookName).first()
        return {
            "code": "0",
            "message:": "SUCCESS",
            "data": book1.getBook
        }
    else:
        return {
            "code": "1",
            "message": "ERROR",
            "data": "未找到指定ID书本"
        }


# @borrow_bp.route('admin/returnUserBook', methods=['POST'])
# def returnUserBook():
#     username = request.json.get('username')
#     bookId = request.json.get('bookId')
#     evaluation = request.json.get('evaluation')
#
#     #获得对象
#     user = Account.query.filter_by(username=username).first()
#     book1 = Book.query.filter_by(bookId=bookId).first()
#     if book1:
#         borrowBook1 = Borrow.query.filter_by(bookName=book1.bookName, username=username).first()
#         if borrowBook1:
#             #修改borrow表
#             borrowBook1.evaluation = evaluation
#             borrowBook1.returnBook = 1
#             db.session.add(borrowBook1)
#             db.session.commit()
#
#             #修改account表和Book表
#             user.borrowBookNum = user.borrowBookNum - 1
#             today = datetime.date.today()
#             #图书损坏严重/图书丢失扣除图书价格
#             if evaluation == 1 or evaluation == 2:
#                 user.money = user.money - book1.price
#                 # 还书超时,没过一天算0.1元
#                 if today > borrowBook1.endDate:
#                     interval = today - borrowBook1.endDate
#                     days = interval.days
#                     user.money = user.money - days * 0.1
#                     db.session.add(user)
#                     db.session.commit()
#                     return {
#                         "code": "0",
#                         "message": "SUCCESS",
#                         "data": "图书损坏或丢失，还书超时"
#                     }
#                 else:
#                     db.session.add(user)
#                     db.session.commit()
#                     return {
#                         "code": "0",
#                         "message": "SUCCESS",
#                         "data": "图书损坏或丢失"
#                     }
#             #图书正常归还，图书库存加1
#             else:
#                 book1.quantity = book1.quantity + 1
#                 db.session.add(book1)
#                 # 还书超时扣10块
#                 if today > borrowBook1.endDate:
#                     user.money = user.money - 10
#                     db.session.add(user)
#                     db.session.commit()
#                     return {
#                         "code": "0",
#                         "message": "SUCCESS",
#                         "data": "还书超时"
#                     }
#                 else:
#                     db.session.add(user)
#                     db.session.commit()
#                     return {
#                         "code": "0",
#                         "message": "SUCCESS",
#                         "data": "还书成功"
#                     }
#         else:
#             return {
#                 "code": "1",
#                 "message": "ERROR",
#                 "data": "未在该用户借阅图书中找到指定ID书本"
#             }
#     else:
#         return {
#             "code": "1",
#             "message": "ERROR",
#             "data": "未在图书馆中找到指定ID书本"
#         }

#未测试
@borrow_bp.route('admin/returnUserBook', methods=['POST'])
def returnUserBook():
    code = request.json.get('code')
    evaluation = request.json.get('evaluation')

    #获得对象
    borrowRecord = Borrow.query.filter_by(code=code).first()
    if borrowRecord:
        user = Account.query.filter_by(username=borrowRecord.username).first()
        book1 = Book.query.filter_by(bookName=borrowRecord.bookName).first()

        #修改borrow表
        borrowRecord.evaluation = evaluation
        borrowRecord.returnBook = 1
        db.session.add(borrowRecord)
        db.session.commit()

        #修改account表和Book表
        user.borrowBookNum = user.borrowBookNum - 1
        today = datetime.date.today()
        #图书损坏严重/图书丢失扣除图书价格
        if evaluation == 1 or evaluation == 2:
            user.money = user.money - book1.price
            # 还书超时,没过一天算0.1元
            if today > borrowRecord.endDate:
                interval = today - borrowRecord.endDate
                days = interval.days
                deduction = Decimal(days) * Decimal('0.1')
                user.money = user.money - deduction
                db.session.add(user)
                db.session.commit()
                return {
                    "code": "0",
                    "message": "SUCCESS",
                    "data": "图书损坏或丢失，还书超时"
                }
            else:
                db.session.add(user)
                db.session.commit()
                return {
                    "code": "0",
                    "message": "SUCCESS",
                    "data": "图书损坏或丢失"
                }
        #图书正常归还，图书库存加1
        else:
            book1.quantity = book1.quantity + 1
            db.session.add(book1)
            # 还书超时扣10块
            if today > borrowRecord.endDate:
                interval = today - borrowRecord.endDate
                days = interval.days
                deduction = Decimal(days) * Decimal('0.1')
                user.money = user.money - deduction
                db.session.add(user)
                db.session.commit()
                return {
                    "code": "0",
                    "message": "SUCCESS",
                    "data": "还书超时"
                }
            else:
                db.session.add(user)
                db.session.commit()
                return {
                    "code": "0",
                    "message": "SUCCESS",
                    "data": "还书成功"
                }

    else:
        return {
            "code": "1",
            "message": "ERROR",
            "data": "未根据二维码在图书馆中找到指定书本"
        }


@borrow_bp.route('getBook', methods=['POST'])
def giveBook():
    username = request.json.get('username')
    bookId = request.json.get('bookId')

    book1 = Book.query.filter_by(bookId=bookId).first()
    if book1:
        borrowBook1 = Borrow.query.filter_by(username=username,bookName=book1.bookName).first()
        if borrowBook1:
            borrowBook1.getBook = 1
            db.session.add(borrowBook1)
            db.session.commit()
            return {
                "code": "0",
                "message": "SUCCESS",
                "data": "借书成功"
            }
        else:
            return {
                "code": "1",
                "message": "ERROR",
                "data": "未在该用户借阅图书中找到指定ID书本"
            }
    else:
        return {
            "code": "1",
            "message": "ERROR",
            "data": "未在图书馆中找到指定ID书本"
        }


@borrow_bp.route('/pageNumber/<string:username>', methods=['GET'])
def pageNumber(username):
    borrowList = Borrow.query.filter_by(username=username).all()
    count = len(borrowList)
    pre_page = 5
    total_pages = count // pre_page + (1 if count % pre_page != 0 else 0)  # 总页数
    return {
        "code": "0",
        "message": "SUCCESS",
        "data": total_pages
    }
